<template>
  <div class="login-container">
    <!-- 动态背景 -->
    <div class="background-animation">
      <div class="gradient-bg"></div>
      <div class="particles">
        <div v-for="i in 50" :key="i" class="particle" :style="getParticleStyle(i)"></div>
      </div>
      <div class="floating-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
        <div class="shape shape-4"></div>
      </div>
    </div>

    <!-- 登录表单 -->
    <div class="login-card">
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <div class="title-container">
          <div class="logo-container">
            <div class="logo-icon">🚀</div>
          </div>
          <h3 class="title">精进坊管理系统</h3>
          <p class="subtitle">超绝无敌炫酷吊炸天版本</p>
        </div>

        <el-form-item prop="username" class="form-item">
          <el-input
            ref="usernameRef"
            v-model="loginForm.username"
            placeholder="输入您的用户名"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
            prefix-icon="User"
            class="custom-input"
          />
        </el-form-item>

        <el-form-item prop="password" class="form-item">
          <el-input
            ref="passwordRef"
            v-model="loginForm.password"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="输入您的密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            prefix-icon="Lock"
            class="custom-input"
            @keyup.enter="handleLogin"
          >
            <template #suffix>
              <el-icon class="show-pwd" @click="passwordVisible = !passwordVisible">
                <component :is="passwordVisible ? 'View' : 'Hide'" />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-button
          :loading="loading"
          type="primary"
          class="login-btn"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">🚀 启动登录</span>
          <span v-else>🌟 正在验证...</span>
        </el-button>

        <div class="footer-text">
          <p>欢迎来到未来科技管理系统</p>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { View, Hide } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref(null)
const usernameRef = ref(null)
const passwordRef = ref(null)
const loading = ref(false)
const passwordVisible = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 粒子动画样式生成
const getParticleStyle = (index) => {
  const size = Math.random() * 4 + 2
  const duration = Math.random() * 20 + 10
  const delay = Math.random() * 5
  const x = Math.random() * 100
  const y = Math.random() * 100
  
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${x}%`,
    top: `${y}%`,
    animationDuration: `${duration}s`,
    animationDelay: `${delay}s`,
    opacity: Math.random() * 0.8 + 0.2
  }
}

onMounted(() => {
  usernameRef.value.focus()
})

const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用真实的登录API
        const response = await request.post('/user/login', {
          userAccount: loginForm.username,
          userPassword: loginForm.password
        })
        
        // 处理登录成功
        if (response && response.code === 0) {
          // 保存用户信息到localStorage
          if (response.data) {
            localStorage.setItem('user_info', JSON.stringify(response.data))
            // 保存token，如果响应中没有token，使用用户ID作为token
            const token = response.data.token || `user_${response.data.id}_${Date.now()}`
            localStorage.setItem('admin_token', token)
          }
          
          ElMessage.success('🎉 登录成功！正在获取用户信息...')
          
          try {
            // 登录成功后立即获取完整的用户信息
            await userStore.fetchUserInfo()
            ElMessage.success('🌟 用户信息加载完成！')
            // 跳转到dashboard
            router.push({ path: '/dashboard' })
          } catch (userInfoError) {
            console.error('获取用户信息失败:', userInfoError)
            // 即使获取用户信息失败，也允许跳转，但给出提示
            ElMessage.warning('登录成功，但获取用户详细信息失败，请稍后刷新页面')
            router.push({ path: '/dashboard' })
          }
        } else {
          // 处理业务错误
          ElMessage.error(response.message || '登录失败，请检查用户名和密码')
        }
      } catch (error) {
        console.error('登录失败:', error)
        
        // 处理网络错误或其他异常
        if (error.response) {
          // 服务器返回了错误状态码
          const errorMsg = error.response.data?.message || '登录失败，服务器错误'
          ElMessage.error(errorMsg)
        } else if (error.request) {
          // 网络请求失败
          ElMessage.error('网络连接失败，请检查网络连接')
        } else {
          // 其他错误
          ElMessage.error('登录失败，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    } else {
      return false
    }
  })
}
</script>

<style scoped>
/* 主容器 */
.login-container {
  min-height: 100vh;
  width: 100%;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 动态渐变背景 */
.background-animation {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.gradient-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    45deg,
    #667eea 0%,
    #764ba2 25%,
    #f093fb 50%,
    #f5576c 75%,
    #4facfe 100%
  );
  background-size: 400% 400%;
  animation: gradientShift 15s ease infinite;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* 粒子效果 */
.particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.particle {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  animation: float linear infinite;
}

@keyframes float {
  0% {
    transform: translateY(100vh) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    transform: translateY(-100px) rotate(360deg);
    opacity: 0;
  }
}

/* 浮动形状 */
.floating-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.shape {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: floatShape 20s ease-in-out infinite;
}

.shape-1 {
  width: 80px;
  height: 80px;
  top: 20%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 60%;
  right: 15%;
  animation-delay: 5s;
}

.shape-3 {
  width: 60px;
  height: 60px;
  bottom: 30%;
  left: 20%;
  animation-delay: 10s;
}

.shape-4 {
  width: 100px;
  height: 100px;
  top: 10%;
  right: 30%;
  animation-delay: 15s;
}

@keyframes floatShape {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 登录卡片 - 玻璃拟态效果 */
.login-card {
  position: relative;
  z-index: 10;
  width: 450px;
  max-width: 90%;
  padding: 40px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
  animation: cardFloat 6s ease-in-out infinite;
}

@keyframes cardFloat {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

.login-form {
  width: 100%;
}

/* 标题区域 */
.title-container {
  text-align: center;
  margin-bottom: 40px;
}

.logo-container {
  margin-bottom: 20px;
}

.logo-icon {
  font-size: 60px;
  animation: logoSpin 3s ease-in-out infinite;
  display: inline-block;
}

@keyframes logoSpin {
  0%, 100% {
    transform: rotate(0deg) scale(1);
  }
  50% {
    transform: rotate(10deg) scale(1.1);
  }
}

.title {
  font-size: 28px;
  color: #fff;
  margin: 0 0 10px 0;
  font-weight: 700;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  background: linear-gradient(45deg, #fff, #f0f8ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-weight: 300;
}

/* 表单项 */
.form-item {
  margin-bottom: 25px;
}

/* 自定义输入框样式 */
:deep(.custom-input .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 12px 15px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

:deep(.custom-input .el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.4);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

:deep(.custom-input .el-input__wrapper.is-focus) {
  background: rgba(255, 255, 255, 0.2);
  border-color: #4facfe;
  box-shadow: 0 0 20px rgba(79, 172, 254, 0.3);
}

:deep(.custom-input .el-input__inner) {
  color: #fff;
  font-size: 16px;
  background: transparent;
}

:deep(.custom-input .el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.custom-input .el-input__prefix-inner) {
  color: rgba(255, 255, 255, 0.7);
}

.show-pwd {
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  transition: all 0.3s ease;
}

.show-pwd:hover {
  color: #4facfe;
  transform: scale(1.1);
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 50px;
  margin-bottom: 30px;
  background: linear-gradient(45deg, #4facfe, #00f2fe);
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.login-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 25px rgba(79, 172, 254, 0.4);
}

.login-btn:hover::before {
  left: 100%;
}

.login-btn:active {
  transform: translateY(-1px);
}

/* 底部文字 */
.footer-text {
  text-align: center;
  margin-top: 20px;
}

.footer-text p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    width: 95%;
    padding: 30px 20px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .logo-icon {
    font-size: 50px;
  }
}
</style>